package com.roc.web.action.terminal;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TPosAgent;
import com.roc.pojo.TblInsInf;
import com.roc.pojo.YjPosBatch;
import com.roc.pojo.YjPosInfo;
import com.roc.service.IMerchantServices;
import com.roc.service.ITerminalService;
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.util.Constance;
import com.roc.util.DateUtil;
import com.roc.util.Utils;
import com.roc.util.constant.ConfigMerinfoUtil;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
import com.roc.util.constant.Terminal;

@Controller
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/terminal")
public class TermYsbSnRevocationAction extends PaginationBaseAction  {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	static Logger logger = LogManager.getLogger(TermYsbSnRevocationAction.class);

	private Long psamCardStartNo;
	private Long psamCardEndNo;
	private Long totalNum;
	private TermYsbSnRevocationSearchCondition searchCondition;

	private List<TblInsInf> orgList = new ArrayList<TblInsInf>();
	private TPosAgent tPosAgent = new TPosAgent();
	
	private InputStream excelFile;
	private String excelName;

	@Autowired
	IPageService pagenitionService;

	@Autowired
	private IorgService orgService;
	
	@Autowired 
	IMerchantServices merchantServices;
	
	@Autowired
	ITerminalService terminalService;
	
	private String serialnums; // sn 数组

	@Action(value = "termYsbRevocationInit", results = { @Result(location = "/pages/terminal/termYsbSnRevQuery.jsp") })
	public String termYsbRevocationInit() throws Exception {
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if( !op.getRoleType().equals(Role.SYSTEM.getCode()) 
				&& !op.getRoleType().equals(Role.O_MANAGER.getCode())
				&& !op.getRoleType().equals(Role.AGENT.getCode())
				&& !op.getRoleType().equals(Role.WARE_HOUSE_LEAD.getCode()) ){
			addActionError("此登陆账号没有权限");
			return ERROR;
		}
		org();
		return SUCCESS;
	}

	@Action(value = "queryYsbRevocationTerminalPosSN", results = { @Result(name = "success", location = "/pages/terminal/termYsbSnRevQuery.jsp") })
	// 查询终端
	public String queryYsbRevocationTerminalPosSN() throws Exception {

		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if (searchCondition == null) {
			searchCondition = (TermYsbSnRevocationSearchCondition) getSearchConditionFromSession();
			if (searchCondition == null) {
				searchCondition = new TermYsbSnRevocationSearchCondition();
			}
		}
		try {
			if( !op.getRoleType().equals(Role.SYSTEM.getCode()) 
					&& !op.getRoleType().equals(Role.O_MANAGER.getCode())
					&& !op.getRoleType().equals(Role.AGENT.getCode())
					&& !op.getRoleType().equals(Role.WARE_HOUSE_LEAD.getCode()) ){
				addActionError("此登陆账号没有权限");
				return ERROR;
			}
			org();

			List<String > snList = new ArrayList<String>();

			if ( Constance.isNotEmpty(searchCondition.getBeginSerialNum()) && !Utils.checkSnCode(searchCondition.getBeginSerialNum()) ) {
				addActionMessage("开始SN号 " + searchCondition.getBeginSerialNum() + " 文字格式不对,请重新输入");
				return ERROR;
			}
			if ( Constance.isNotEmpty(searchCondition.getEndSerialNum()) && !Utils.checkSnCode(searchCondition.getEndSerialNum()) ){
				addActionMessage("结束SN号 " + searchCondition.getEndSerialNum() + " 文字格式不对,请重新输入");
				return ERROR;
			}
			
			
			if ( Constance.isNotEmpty(searchCondition.getBeginSerialNum()) && Constance.isNotEmpty(searchCondition.getEndSerialNum()) ) {
				TPosAgent bean = new TPosAgent();
				bean.setBeginSerialNum(searchCondition.getBeginSerialNum().trim());
				bean.setEndSerialNum(searchCondition.getEndSerialNum().trim());
		        // 判断是否是同一个号段
		        boolean flag = getUnContSNInfo(bean);
		        if( !flag ){
		        	addActionMessage("撤回的sn号号段 不是同一个号段，请确认!");
		        	return SUCCESS;
		        }
		        // 通过开始SN和结束SN 取所有的SN
		        snList = getSnList (bean);
		        
		        if ( snList.size() > Constance.YSB_POS_SN_SELECT_MAX_SIZE ) {
		        	addActionMessage("撤回的sn号号段 长度太长，请重新输入!");
		        	return SUCCESS;
		        }
			} else  if ( Constance.isNotEmpty(searchCondition.getBeginSerialNum()) )
				snList.add( Utils.changeCharUpperCase( searchCondition.getBeginSerialNum() ) );

			searchCondition.setSnList(snList);

			searchCondition.setOpRoleType(op.getRoleType());
			searchCondition.setAccountId(op.getId());
			
			int rows = pagenitionService.countSQL(searchCondition);

			searchRsList = pagenitionService.findAllSQL(searchCondition,
					calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);

			List<YjPosInfo> posList = new ArrayList<YjPosInfo>();
			if (searchRsList != null && searchRsList.size() > 0) {
				Iterator iterator = searchRsList.iterator();
				while (iterator.hasNext()) {
					Object[] obj = (Object[]) iterator.next();
					YjPosInfo pos = new YjPosInfo();
					pos.setSerialNum(Constance.Null2EmptyTrim(obj[0]));

					String brandCode = obj[1] + "";
					String typeCode = obj[2] + "";
					String nameCode = obj[3] + "";
					
					pos.setPosBrand(ConfigMerinfoUtil.getPosBRAND(brandCode));
					pos.setPosName(ConfigMerinfoUtil.getPosMODEL(nameCode , brandCode));
					pos.setPosType(ConfigMerinfoUtil.getTerminalType(typeCode));
					
					pos.setOrgCode(Constance.Null2EmptyTrim(obj[4]));
					pos.setIsBind(Terminal.valueOfCode(
							Constance.Null2EmptyTrim(obj[5])).getName());
					pos.setMercCode(Constance.Null2EmptyTrim(obj[6]));
					pos.setTermCode(Constance.Null2EmptyTrim(obj[7]));
					pos.setRemark(Constance.Null2EmptyTrim(obj[8]));
					pos.setInDateStr(DateUtil.formatTime(Constance
							.Null2EmptyTrim(obj[9])));
					pos.setOutDateStr(DateUtil.formatTime(Constance
							.Null2EmptyTrim(obj[10])));
					pos.setAgentName(Constance.Null2EmptyTrim(obj[11]));
					pos.setOperators(Constance.Null2EmptyTrim(obj[12]));
					// 厂商编号
					pos.setPosBrandCode(brandCode);
					if ( !"".equals( Constance.Null2EmptyTrim(obj[13]) ) ){
						pos.setTekId(Terminal.valueOfCode(
								Constance.Null2EmptyTrim(obj[13])).getName());
					}
					posList.add(pos);
				}
			}
			searchRsList.clear();
			searchRsList.addAll(posList);
			dealWithTheListSpecially(searchRsList);
			getRequest().setAttribute("posList", posList);
			getRequest().setAttribute("selModelCode", searchCondition.getPosName());
			getRequest().setAttribute("oldBandCode", searchCondition.getPosBrand());
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
		}

		return SUCCESS;
	}

	private void org() {
		Operators loginOperator = (Operators) ActionContext.getContext()
				.getSession().get(Constant.SESSION_LOGIN_MERCHANT);
		try {
			TblInsInf inf = new TblInsInf();
			orgList=orgService.listOrg(inf);

			getRequest().setAttribute("brandMap",ConfigProperties.getYsbBrandProperties());
			getRequest().setAttribute("nameMap", new ArrayList<Map<String,Object>>());
			getRequest().setAttribute("typeMap", ConfigProperties.getSysDB1("Terminal_Type",true));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		ActionContext.getContext().put("merchantList", null);
	}

	@Action(value = "termYsbRevJsp", results = { @Result(location = "/pages/terminal/termYsbSnRevocation.jsp") })
	public String termYsbRevJsp() throws Exception {
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if( !op.getRoleType().equals(Role.SYSTEM.getCode()) 
				&& !op.getRoleType().equals(Role.O_MANAGER.getCode())
				&& !op.getRoleType().equals(Role.AGENT.getCode())
				&& !op.getRoleType().equals(Role.WARE_HOUSE_LEAD.getCode()) ){
			addActionError("此登陆账号没有权限");
			return ERROR;
		}
		org();
		return SUCCESS;
	}

	protected void dealWithTheListSpecially(List<Object> list) {
		super.dealWithTheListSpecially(list);
		Map<String, String> roleTypes = ConfigProperties
				.getRoleTypeProperties();
		List<Object> tempList = new ArrayList<Object>();
		for (Object obj : list) {
			YjPosInfo pos = (YjPosInfo) obj;
			for (TblInsInf bean : orgList) {
				if (pos.getOrgCode().equals(bean.getInsIdCd())) {
					pos.setOrgName(bean.getInsName());
				}
			}

			tempList.add(pos);
		}
		searchRsList = tempList;
	}

	@Action(value = "revYsbTerminalPosSN", results = {
			@Result(name = SUCCESS,type="chain", location = "termYsbRevJsp"),
			@Result(name = "error", location = "/error.jsp") 
			})
	public String revYsbTerminalPosSN() throws Exception {
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		List<String> noExistsList = new ArrayList<String>();
		try {

			if( null == tPosAgent.getBeginSerialNum() || "".equals(tPosAgent.getBeginSerialNum().trim()) ){
				addActionMessage("请输入开始号段");
				return ERROR;
			}
			if( null == tPosAgent.getEndSerialNum() || "".equals(tPosAgent.getEndSerialNum().trim()) ){
				addActionMessage("请输入结束号段");
				return ERROR;
			}
			if (!Utils.checkSnCode(tPosAgent.getBeginSerialNum())) {
				addActionMessage("开始SN号 " + tPosAgent.getBeginSerialNum() + " 文字格式不对,请重新输入");
				return ERROR;
			}
			if (!Utils.checkSnCode(tPosAgent.getEndSerialNum())){
				addActionMessage("结束SN号 " + tPosAgent.getEndSerialNum() + " 文字格式不对,请重新输入");
				return ERROR;
			}

	        // 判断是否是同一个号段
	        boolean flag = getUnContSNInfo(tPosAgent);
	        if( !flag ){
	        	addActionMessage("撤回的sn号号段 不是同一个号段，请确认!");
	        	return SUCCESS;
	        }

	        noExistsList = terminalService.revYsbTerminalPosSNInfo(tPosAgent, op);
		} catch (ServiceException e) {
			e.printStackTrace();
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			return ERROR;
		}
		String msg = "sn序列号撤回成功！";
		if ( null != noExistsList && 0 < noExistsList.size() ) {
			msg = "选择的sn序列中部分sn序列号在系统中不存在或未分配，请确认！！！ ！ 系统不存在或未分配的sn序列号如下:" + noExistsList.toString() ;
		}
    	addActionMessage(msg);
		return SUCCESS;
	}

	private List<String > getSnList (TPosAgent bean){
		List<String > retList = new ArrayList<String>();

		String beginSn = Utils.changeCharUpperCase( bean.getBeginSerialNum() );
		String endSn = Utils.changeCharUpperCase( bean.getEndSerialNum() );
		int nums = bean.getNums();
		// 取SN最后一个字符的位置,便于分割
		int bLastChar = Constance.getSNLastCharPlace(beginSn);

		String bChars = getChar(bLastChar, beginSn);
		String bNumber = getSnNumber(bLastChar, beginSn);
		Long number = -1l;
		if( null != bNumber && !"".equals( bNumber )) {
			number = Long.parseLong( bNumber );
		}
		int zeroLength = beginSn.length() - bChars.length() - String.valueOf( number ).length();
		for ( int s = 1; s <= nums; s++) {
			Long lastNumber = number - 1;
			
			if( String.valueOf( number ).length() > String.valueOf( lastNumber ).length() ) {
				zeroLength = zeroLength - 1;
			}
			String serialNum = bChars ;
			if ( number != -1l ) {
				serialNum = serialNum + Utils.addLeftZero(zeroLength, number);
			}
			String sn = Utils.changeCharUpperCase( serialNum );
			retList.add(sn);
			number++;
		}
		return retList;
	}

	private boolean getUnContSNInfo( TPosAgent info){
		boolean flag = false;
		try {
			String beginSn = info.getBeginSerialNum().trim();
			String endSn = info.getEndSerialNum().trim();

			// 第一个SN 的长度,
			int bLength = beginSn.length();
			// 取SN最后一个字符的位置,便于分割
			int bLastChar = Constance.getSNLastCharPlace(beginSn);

			String bChars = getChar(bLastChar, beginSn);
			String bNumber = getSnNumber(bLastChar, beginSn);

			// 最后一个SN 的长度,
			int eLength = endSn.length();
			// 取SN最后一个字符的位置,便于分割
			int eLastChar = Constance.getSNLastCharPlace(endSn);

			String eChars = getChar(eLastChar, endSn);
			String eNumber = getSnNumber(eLastChar, endSn);

			if( bLength == eLength && bLastChar == eLastChar && bChars.equals(eChars) && (
					( ( null == bNumber || "".equals(bNumber) ) && ( null == eNumber || "".equals(eNumber) ) ) 
					|| 
					(  Long.parseLong(bNumber) <= Long.parseLong(eNumber) )
					)  ){
				flag = true;
				if (  ( null == bNumber || "".equals(bNumber) ) && ( null == eNumber || "".equals(eNumber) )  ){
					info.setNums( 1 );
				}else {
					info.setNums(  Integer.parseInt( String.valueOf( Long.parseLong(eNumber) - Long.parseLong(bNumber) ) ) + 1 );
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
		}
		return flag;
	}

	private String getChar( int lastChar ,String sn ){
		String bChars = "";
		if( lastChar >= 0){
			bChars = sn.substring(0, lastChar + 1);
		}
		return bChars;
	}
	
	private String getSnNumber( int lastChar ,String sn ){
		String bNumber = "";
		if ( lastChar < ( sn.length()-1 ) ){
			bNumber = sn.substring( ( lastChar== -1 ? 0 : lastChar + 1 ), sn.length() );
		}
		return bNumber;
	}
	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE + "";
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (TermYsbSnRevocationSearchCondition) getSession().getAttribute(
				SEARCH_SESSION_YSB_SN_REVOCATION);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);

	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_YSB_SN_REVOCATION,
				searchCondition);
	}

	public Long getPsamCardStartNo() {
		return psamCardStartNo;
	}

	public void setPsamCardStartNo(Long psamCardStartNo) {
		this.psamCardStartNo = psamCardStartNo;
	}

	public Long getPsamCardEndNo() {
		return psamCardEndNo;
	}

	public void setPsamCardEndNo(Long psamCardEndNo) {
		this.psamCardEndNo = psamCardEndNo;
	}

	public Long getTotalNum() {
		return totalNum;
	}

	public void setTotalNum(Long totalNum) {
		this.totalNum = totalNum;
	}

	public List<TblInsInf> getOrgList() {
		return orgList;
	}

	public void setOrgList(List<TblInsInf> orgList) {
		this.orgList = orgList;
	}

	public TermYsbSnRevocationSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(TermYsbSnRevocationSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}

	public String getExcelName() {
		return excelName;
	}

	public void setExcelName(String excelName) {
		this.excelName = excelName;
	}

	public String getSerialnums() {
		return serialnums;
	}

	public void setSerialnums(String serialnums) {
		this.serialnums = serialnums;
	}
	public TPosAgent gettPosAgent() {
		return tPosAgent;
	}
	public void settPosAgent(TPosAgent tPosAgent) {
		this.tPosAgent = tPosAgent;
	}
	


}
